//      qtavrdude.cpp
//      
//      Copyright 2011 mdchaparror <mdchaparror@gmail.com>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.


#include "qtavrdude.h"
#include "ui_qtavrdude.h"
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <iostream>
#include <QMessageBox>
#include <QtWebKit/QWebView>
#include <stdio.h>


using namespace std;
QString puerto="usb";
qtavrdude::qtavrdude(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::qtavrdude)

{
  ui->setupUi(this);
  QFile file(QString::fromUtf8(":/new/prefix1/Dispositivos.dat"));
  file.open(QIODevice::ReadOnly | QIODevice::Text);
  QTextStream in(&file);
  while (!in.atEnd()) {
    ui->Microcontrolador->addItem(in.readLine());
    
  }
  
  file.close();
  avrdude=0;

}

qtavrdude::~qtavrdude()
{
  delete ui;
}

void qtavrdude::on_Cargar_archivo_clicked()
{
  QString fileName = QFileDialog::getOpenFileName(this,"cargar archivo","","Standard Intel HEX files(*.hex)");
  ui->FileName->setText(fileName);
  statusBar()->showMessage(tr("archivo: %1").arg(fileName),2000);
}

void qtavrdude::on_Read_fuse_clicked()
{
  
  QString comando ="avrdude -c  -p  -P  -v -U hfuse:r:-:h -U lfuse:r:-:h ";
  comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
  comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
  comando.insert(comando.indexOf("-P ")+3,puerto);
  execute_avrdude(&comando);

  cout<<comando.toStdString()<<endl;
  
}

void qtavrdude::on_erase_clicked()
{
  QString comando="avrdude -c  -p   -P  -e  -v";
  comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
  comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
  comando.insert(comando.indexOf("-P ")+3,puerto);
  execute_avrdude(&comando);
  statusBar()->showMessage("memoria flash del AVR borrada", 2000);
  cout<<comando.toStdString()<<endl;
}

void qtavrdude::on_Load_clicked()
{
  QString comando="avrdude -c  -P  -p   -U flash:w: :i";
  if(!ui->FileName->text().isEmpty()){
    comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
    comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
    comando.insert(comando.indexOf("-P ")+3,puerto);
    comando.insert(comando.indexOf("flash:w:")+8,ui->FileName->text());

    execute_avrdude(&comando);
    statusBar()->showMessage("memoria flash del AVR programada", 2000);
    cout<<comando.toStdString()<<endl;
  }
  else{
    QMessageBox::warning(this, tr("QtAvrdude"),"No se ha seleccionado un archivo para programar");
    statusBar()->showMessage(tr("No se ha seleccionado un archivo para programar"), 2000);
    
  }
}

void qtavrdude::on_Terminal_clicked()
{
  system("gnome-terminal");
  
}

void qtavrdude::on_save_clicked()
{
  QString filename= QFileDialog::getSaveFileName(this,"guardar archivo ","avrdude_log.txt", "txt(*.txt)");
  QFile file(filename);
  if (!file.open(QFile::WriteOnly | QFile::Text)) {
    QMessageBox::warning(this, tr("QtAvrdude"), tr("no se puede guardar el archivo:  %1:\n%2.").arg(filename).arg(file.errorString()));
    return ;
  }
  
  QTextStream out(&file);
  QApplication::setOverrideCursor(Qt::WaitCursor);
  out << ui->salida->toPlainText();
  QApplication::restoreOverrideCursor();
  statusBar()->showMessage(tr("File saved"), 2000);
  return ;
}


void qtavrdude::on_Verificar_clicked()
{
  QString comando="avrdude -c  -p  -P  -U flash:v: :i  -v";
  if(!ui->FileName->text().isEmpty()){
    comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
    comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
    comando.insert(comando.indexOf("flash:v:")+8,ui->FileName->text());
    comando.insert(comando.indexOf("-P ")+3,puerto);
    execute_avrdude(&comando);
    statusBar()->showMessage("memoria flash del AVR programada", 2000);

    cout<<comando.toStdString()<<endl;
  }
  else{
    QMessageBox::warning(this, tr("QtAvrdude"),"No se ha seleccionado un archivo para Verificar ");
    statusBar()->showMessage(tr("No se ha seleccionado un archivo para verificar"), 2000);
    
  }
}
void qtavrdude::execute_avrdude(QString *l){

  if(avrdude!=0)
    finish_avrdude();
  ui->salida->append("<b><font color='RED'>COMANDO:   <b><font color='blue'>"+l->toAscii());
    avrdude = new callApp(l->toAscii());
    connect(avrdude,SIGNAL(newData()),this,SLOT(out_avrdude()));
    connect(avrdude,SIGNAL(appClosed()),this,SLOT(finish_avrdude()));
}

void qtavrdude::on_lfok_clicked()
{
  QString comando="avrdude -c  -p  -P  -U lfuse:w::m";
  if(!ui->lfuse->text().isEmpty()){
    comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
    comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
    comando.insert(comando.indexOf("lfuse:w:")+8,ui->lfuse->text());
    comando.insert(comando.indexOf("-P ")+3,puerto);
    execute_avrdude(&comando);
    cout<<comando.toStdString()<<endl;
  }
  else{
    ui->salida->append("valor lfuse no asignado");
  }
}

void qtavrdude::on_hfok_clicked()
{
  QString comando="avrdude -c  -p  -P  -U hfuse:w::m";
  if(!ui->hfuse->text().isEmpty()){
    comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
    comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
    comando.insert(comando.indexOf("hfuse:w:")+8,ui->hfuse->text());
    comando.insert(comando.indexOf("-P ")+3,puerto);
    execute_avrdude(&comando);
    cout<<comando.toStdString()<<endl;
  }
  else{
    ui->salida->append("valor hfuse no asignado");
  }
}

void qtavrdude::on_efok_clicked()
{
    QString comando="avrdude -c  -p  -P  -U efuse:w::m";
    if(!ui->hfuse->text().isEmpty()){
      comando.insert(comando.indexOf("-c ")+3,ui->Programador->currentText());
      comando.insert(comando.indexOf("-p ")+3,ui->Microcontrolador->currentText());
      comando.insert(comando.indexOf("efuse:w:")+8,ui->hfuse->text());
      comando.insert(comando.indexOf("-P ")+3,puerto);
      execute_avrdude(&comando);
      cout<<comando.toStdString()<<endl;
  }
  else{
    ui->salida->append("valor efuse no asignado");
  }
}
void qtavrdude::out_avrdude()
{

  QString newData = avrdude->readData();
  ui->salida->append(newData);

}
void qtavrdude::finish_avrdude()
{
  if(avrdude!=0)
    avrdude->deleteProcess();
  avrdude->deleteLater();
  avrdude=0;

}

void qtavrdude::on_Info_micro_clicked()
{
    QString temp;
    QString fil=":/new/prefix1/Info/"+ui->Microcontrolador->currentText()+".html";
    QFile file(fil);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream in(&file);
    while (!in.atEnd()) {
      temp+=in.readLine();

    }

    file.close();
ui->salida->append(temp);
}

void qtavrdude::on_Programador_currentIndexChanged(const QString &arg1)
{
    puerto="usb";
    if(arg1=="bsd") puerto="/dev/parport0";
}
void qtavrdude::set_argumento(char *l)
{ui->FileName->setText(QString::fromUtf8(l));}
